import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class CASDemo {

    private int num = 0;

    public int getNum() {
        return num;
    }

    public synchronized void setNum() {
        num++;
    }

    private AtomicInteger atomicInteger = new AtomicInteger(0);

    public AtomicInteger getAtomicInteger() {
        return atomicInteger;
    }

    public void setAtomicInteger() {
//        atomicInteger.incrementAndGet();//++i
        //为什么原子类不加锁就能实现原子性
        atomicInteger.getAndIncrement();//i++
    }

    public static void main(String[] args) throws InterruptedException {

//        AtomicInteger atomicInteger = new AtomicInteger(4);
//        返回的是bool值 返回是否修改成功
//        boolean b = atomicInteger.compareAndSet(4, 6);
//        atomicInteger.compareAndSet(4, 5);
//        System.out.println(atomicInteger);
        CASDemo casDemo = new CASDemo();
        Lock lock = new ReentrantLock();
        int temp=100;
        CountDownLatch countDownLatch = new CountDownLatch(temp);

        for (int i = 1; i <= temp; i++) {
            new Thread(() -> {
                for (int j = 1; j <= 100; j++) {
                    casDemo.setNum();
                    casDemo.setAtomicInteger();
                }
                countDownLatch.countDown();
            }, String.valueOf(i)).start();
        }

//        TimeUnit.SECONDS.sleep(1);
        countDownLatch.await();
        System.out.println(casDemo.getAtomicInteger());
        System.out.println(casDemo.getNum());

    }

}
